<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 视图部分 -->
    <el-card style="margin-top:1%;">
      <!-- 告示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row style="margin-top:1%;">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 商品级联选择 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            expand-trigger="hover"
            :props="cateProp"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!--  -->
      <el-row style="margin:1%;">
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数面板 -->
            <el-tab-pane label="动态参数" name="many">
              <el-button
                type="primary"
                icon="el-icon-plus"
                :disabled="isBtnDisabled"
                @click="addDialogVisible = true"
                >添加参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table
                :data="manyTabData"
                border="true"
                stripe="true"
                style="margin-top:1%;text-align:center;"
              >
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <!-- 循环渲染tag标签 -->
                    <el-tag
                      v-for="(item, i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close = "handClose(i,scope.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 输入文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <!-- 添加tag的按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <!-- 参数名称 -->
                <el-table-column
                  prop="attr_name"
                  label="参数名称"
                  style="text-align:center;"
                ></el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 根据参数id修改 -->
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row.attr_id)"
                      >修改</el-button
                    >
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="removeParams(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加静态属性面板 -->
            <el-tab-pane label="静态属性" name="only" icon="el-icon-plus">
              <el-button
                type="primary"
                icon="el-icon-plus"
                :disabled="isBtnDisabled"
                @click="addDialogVisible = true"
                >静态属性</el-button
              >
              <!-- 静态属性面板 -->
              <el-table
                :data="onlyTabData"
                border="true"
                stripe="true"
                style="margin-top:1%;text-align:center;"
              >
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <!-- 循环渲染tag标签 -->
                    <el-tag
                      v-for="(item, i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close = "handClose(i,scope.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 输入文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <!-- 添加tag的按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <!-- 参数名称 -->
                <el-table-column
                  prop="attr_name"
                  label="属性名称"
                ></el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row.attr_id)"
                      >修改</el-button
                    >
                    <el-button type="danger" size="mini" icon="el-icon-delete"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加参数 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 弹窗文本 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 弹窗文本 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除参数 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      catelist: [],
      cateProp: {
        value: "cat_pid",
        label: "cat_name",
        children: "children"
      },
      //   页签的默认选中
      activeName: "many",
      // 被选中的数据ID
      selectedCateKeys: [],
      //动态参数列表
      manyTabData: [],
      // 静态属性列表
      onlyTabData: [],
      // 添加参数对话框
      addDialogVisible: false,
      // 添加参数表单
      addForm: {
        attr_name: ""
      },

      addFormRules() {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: blur
          }
        ];
      },
      // 修改表单
      editForm: {},
      // 控制修改对话框
      editDialogVisible: false,
      // 修改对话框表单验证
      editFormRules() {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: blur
          }
        ];
      },
      // 控制标签显示的样式
      inputVisible: false,
      // 文本框输入内容
      inputValue: ""
    };
  },
  created() {
    // 获取商品分类数据
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 }
      });
      if (res.meta.status !== 200) {
        return this.$message.console.error("获取商品数据失败！");
      }

      // 获取成功
      this.catelist = res.data;
    },
    // 级联数据发生变化时触发
    handleChange() {
      this.getParamsData();
    },
    handleTabClick() {
      this.getParamsData();
    },
    async getParamsData() {
      // 证明选中的不是三级分类,清空选中的数组
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        // 解决父级分类发生改变时，子类参数还在的问题
        this.manyTabData = []
        this.onlyTabData = []
        return;
      }
      // 如果是三级分类，就根据选择的id和面板发起网络数据请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      // 判断请求是否成功
      if (res.meta.status !== 200) {
        return this.$message.error("请求参数失败");
      }

      // 把attr_value 里面的数据变成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 控制文本框的显示
        item.inputVisible = false;
        // 文本框的值
        item.inputValue = "";
      });
      console.log(res.data);
      // 判断获取的数据是哪个模块的
      if (this.activeName === "many") {
        this.manyTabData = res.data;
      } else {
        this.onlyTabData = res.data;
      }
    },
    // 监听对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听修改对话框
    editDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 提交表单
    addParams() {
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        // 失败
        if (!valid) {
          return this.$message.error("预验证失败");
        }
        // 预验证成功,发起网络请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        // 判断请求是否成功
        // 失败
        if (res.meta.status !== 201) {
          return this.$message.error("请求体参数失败");
        }

        // 成功
        this.$message.success("请求体参数成功！");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 展示修改对话框
    async showEditDialog(attr_id) {
      // 首先根据传过来的参数id将参数名称显示到弹窗上，在调用修改接口提交数据

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );
      // 请求失败
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败！");
      }
      // 请求成功
      this.editForm = res.data;

      this.editDialogVisible = true;
    },
    // 点击按钮，修改对话框
    editParams() {
      // 首先进行预验证
      this.$refs.editFormRef.validate(async valid => {
        // 预验证失败
        if (!valid) {
          return this.$message.error("预验证失败！");
        }
        // 预验证成功，调用参数修改接口
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        );

        // 调用失败
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }

        // 修改成功
        this.$message.success("修改参数成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 删除参数
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      //取消了本次删除
      if (confirmResult !== "confirm") {
        return this.$message.info("你取消了删除！");
      }
      // 调用删除参数接口
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除参数失败！");
      }

      this.$message.success("删除成功！");
      this.getParamsData();
    },
    // 失去焦点或是按下了enter键

   async handleInputConfirm(row) {
      // 如果只输入了空格，则调用trim函数清空空格并重新赋值给文本
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 把新增加的标签添加到attr_vals里面
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals()

    },
    // 对attr_vals的操作
    async saveAttrVals(row){
      // 调用接口，上传数据
      const { data : res }= await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      // 判断请求是否成功
      if(res.meta.status !== 200){
        return this.$message.error('修改标签失败！')
      }
      
      // 添加成功
      this.$message.success(
        '修改参数成功'
      )
    },

    // 显示文本
    showInput(row) {
      row.inputVisible = true
      // 页面上的元素被重新渲染才会调用nexttick中的回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除标签
    handClose(i,row){
      // 删除第i个标签
      row.attr_vals.splice(i,1)

      this.saveAttrVals(row)
    }

  },
  //   监听是否有数据来判断是否可以用表格
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    //   当前的选中的三级数据的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      } else {
        return null;
      }
    },
    // 弹出框标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>